﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Home.Haushalt.Lib;
using System.Diagnostics;
using System.Threading;
using Home.Haushalt.Lib.Element;

namespace Home.Haushalt.Gui
{
    /// <summary>
    /// 
    /// </summary>
    public partial class FrmAutoLogin : Form
    {
        /// <summary></summary>
        public event EventHandler<HEventArgs> OnAction;

        /// <summary></summary>
        private string _formName = "";

        /// <summary></summary>
        private string _autologinBody = "";

        /// <summary></summary>
        private ElementBase _elementBase;

        #region STATIC METHODS

        ///// <summary>
        ///// 
        ///// </summary>
        ///// <param name="memberID"></param>
        ///// <returns></returns>
        //public static bool AutoLoginExists(int memberID)
        //{
        //    string filePath = Path.Combine(DAO.AutologinFilesPath, memberID.ToString() + ".cry");
        //    return File.Exists(filePath);
        //}

        ///// <summary>
        ///// 
        ///// </summary>
        ///// <param name="memberID"></param>
        ///// <returns></returns>
        //public static bool DeleteAutoLoginFile(int memberID)
        //{
        //    return Chips.FileTryDelete(Path.Combine(DAO.AutologinFilesPath, memberID.ToString() + ".cry"));
        //}

        /// <summary>
        /// 
        /// </summary>
        /// <param name="memberID"></param>
        public static void StartAutoLogin(int memberID)
        {
            //string targetFilePath = Path.Combine(DAO.AutologinFilesPath, memberID.ToString() + ".htm");

            //StreamReader sr = new StreamReader(Path.Combine(DAO.AutologinFilesPath, memberID.ToString() + ".cry"));
            //string encryptContnet = sr.ReadToEnd();
            //sr.Close();

            //StreamWriter sw = new StreamWriter(targetFilePath, false);
            //sw.Write(DAO.Credential.CurrentCry.Decrypt64(encryptContnet));
            //sw.Close();

            string targetFilePath = DAO.HFile.DecriptAutoLoginFile(memberID);

            Process.Start(targetFilePath);

            bool fileDeleted = false;
            for (int index = 0; index < 10; index++)
            {
                Thread.Sleep(3000);

                fileDeleted = Chips.FileTryDelete(targetFilePath);
                if (fileDeleted)
                    break;

                Application.DoEvents();
            }

            if (!fileDeleted)
            {
                Journal.Add(typeof(FrmAutoLogin), ActionResult.Nok, "Login-Datei [" + targetFilePath + "] konnte nicht gelöscht werden!");
            }
        }

        #endregion STATIC METHODS

        /// <summary>
        /// 
        /// </summary>
        /// <param name="elementBase"></param>
        public FrmAutoLogin(ElementBase elementBase)
        {
            InitializeComponent();

            _elementBase = (Member)elementBase;

            cbMethod.SelectedIndex = 0;

            txtLink.Text = _elementBase.Row[Member.Fields.Link].ToString();

            Reload();
        }

        /// <summary>
        /// 
        /// </summary>
        private void Reload()
        {
            _formName = "";
            _autologinBody = "";

            btnSave.Enabled = false;
            lblStatus.Text = "Neu laden...";

            if (txtLink.Text.Length > 0)
            {
                wbAutologin.Navigate(txtLink.Text);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void wbAutologin_OnFormInput(object sender, HWebBrowser.FormInputEventArgs e)
        {
            if (_formName.Length == 0 || _formName == e.FormName)
            {
                _formName = e.FormName;
                _autologinBody = e.FormString;

                lblStatus.Text = "Aktuelles Formular ist gesetzt";

                btnSave.Enabled = true;
            }
            else if (_formName.Length > 0)
            {
                if (MessageBox.Show("Die Eingabe war ausserhalb des aktuellen internen Formulars! Nur Daten vom aktuellen Formular werden gespeichert.\n\nSoll das neue Formular als aktueller markiert werden?"
                    , "", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    _formName = e.FormName;
                    _autologinBody = e.FormString;
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void wbAutologin_ProgressChanged(object sender, WebBrowserProgressChangedEventArgs e)
        {
            int max = (int)e.MaximumProgress;

            int index = (int)e.CurrentProgress;
            index = (index < pbProzess.Minimum) ? pbProzess.Minimum : index;
            index = (index > max) ? max : index;

            pbProzess.Maximum = max;
            pbProzess.Value = index;

            if (e.MaximumProgress == e.CurrentProgress)
                lblStatus.Text = "Bereit";
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            DAO.HFile.CreateAutoLoginFile(_elementBase.ID, _autologinBody);
            //StreamWriter sw = new StreamWriter(Path.Combine(DAO.AutologinFilesPath, _elementBase.ID.ToString() + ".cry"), false);
            //try
            //{
            //    sw.Write(DAO.Credential.CurrentCry.Encrypt64(_autologinBody));
            //    sw.Close();
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show("Aktion gescheitert: " + ex.Message);
            //    if (sw != null) sw.Close();
            //}

            if (OnAction != null)
                OnAction(this, new HEventArgs(""));

            Close();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmAutoLogin_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (OnAction != null)
                OnAction(this, new HEventArgs(""));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void wbAutologin_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            txtLink.Text = e.Url.ToString();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtLink_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Reload();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReset_Click(object sender, EventArgs e)
        {
            Reload();
        }
    }

}
